function Fn() { }

// #ifdef MP_WEIXIN
const app = getApp().$vm.$options; // 全局变量
//console.log('MP_WEIXIN,app=',app)
// #endif

// #ifdef MP_ALIPAY
import app from './appUtil'
// #endif

// var crc = app.requirejs("crc16");
import crc from './crc16.js';
Fn.prototype = {
    //领取设备出货二进制数组整合，下沙蓝牙主板
    Active: function (ordersn, type, num, times) {
        var buffer = new ArrayBuffer(18)//发送出货需要20个字节
        var dataView = new Uint8Array(buffer)
        dataView[0] = 67 //ascii 代表C
        dataView[1] = 18 //帧长度20
        dataView[2] = 2 //帧类型-微信发送给设备
        dataView[3] = 0 //帧序号 -- 变量 0-255
        dataView[4] = 13 //数据区的长度
        dataView[5] = 3 //命令出货 0x03
        dataView[6] = parseInt(type, 16) //硬件类型 0x65(弹簧套餐) 0x66(电磁锁)---变量
        var i = 1
        for (i = 1; i <= 8; i++) {
            dataView[6 + i] = parseInt(ordersn.substr((i - 1) * 2, 2), 10)
            //console.log(ordersn.substr((i-1)*2, 2))
        }
        dataView[15] = num //套餐号 1-128
        dataView[16] = times //出货次数，最大为20，最小为1
        var check = 0
        for (let byte of dataView) {
            check += byte
        }
        dataView[17] = check //把和直接赋值，因为dataView 是Uint8 所以，直接就可以取低8位
        return buffer
    },
    //广州蓝牙主板 最新协议
    Touch: function (ordersn, goodway, led, led_time, device_sn, key = '') {
        if (!key) {
            key = app.globalData.key
        }
        var buffer = new ArrayBuffer(20); //发送出货需要20个字节
        var dataView = new Uint8Array(buffer);
        dataView[0] = 126; // 16进制  7E
        dataView[1] = 1; //数据标识，
        var i = 1
        for (i = 1; i <= 6; i++) {    //设备编号
            dataView[1 + i] = parseInt(device_sn.substr((i - 1) * 2, 2), 16)
            //console.log(device_sn.substr((i - 1) * 2, 2))
        }
        dataView[8] = 0; //扩展区，默认00
        dataView[9] = 0; //扩展区，默认00
        dataView[10] = 160; //开锁命令 A0
        dataView[11] = goodway; //第几套餐
        dataView[12] = led; //led是否亮
        dataView[13] = led_time ? led_time : 15; //led亮灯时间，默认15s

        //订单号4个字节
        for (i = 1; i <= 4; i++) {
            dataView[13 + i] = parseInt(ordersn.substr((i - 1) * 2, 2), 10)
            //console.log(ordersn.substr((i-1)*2, 2))
        }
        var check = 0
        dataView[18] = 0 //把和直接赋值，因为dataView 是Uint8 所以，直接就可以取低8位
        check = crc.veri(dataView, key)
        //console.log(check)
        dataView[19] = parseInt(check.substr(2, 2), 16)
        //console.log(dataView)
        return buffer
    },
    //广州蓝牙主板-充电
    Charge: function (ordersn, charge_time, device_sn, key = '') {
        if (!key) {
            key = app.globalData.key
        }
        if (charge_time < 1) {
            return false
        }
        var buffer = new ArrayBuffer(20); //发送出货需要20个字节
        var dataView = new Uint8Array(buffer);
        dataView[0] = 126; // 16进制  7E
        dataView[1] = 1; //数据标识，
        var i = 1
        for (i = 1; i <= 6; i++) {    //设备编号
            dataView[1 + i] = parseInt(device_sn.substr((i - 1) * 2, 2), 16)
            //console.log(device_sn.substr((i - 1) * 2, 2))
        }
        dataView[8] = 0; //扩展区，默认00
        dataView[9] = 0; //扩展区，默认00
        dataView[10] = 160; //开锁命令 A0
        dataView[11] = 1; //第几套餐
        dataView[12] = 1; //标识要充电
        dataView[13] = charge_time; //充电时间基本单位是 分钟

        //订单号4个字节
        for (i = 1; i <= 4; i++) {
            dataView[13 + i] = parseInt(ordersn.substr((i - 1) * 2, 2), 10)
            //console.log(ordersn.substr((i-1)*2, 2))
        }
        var check = 0
        dataView[18] = 0 //保留1个字节
        check = crc.veri(dataView, key)
        //console.log(check)
        dataView[19] = parseInt(check.substr(2, 2), 16)
        console.log(dataView)
        return buffer
    },
    //广州蓝牙主板 他们自己的协议
    Touchold: function (goodway, led, led_time, device_sn) {
        var buffer = new ArrayBuffer(20); //发送出货需要20个字节
        var dataView = new Uint8Array(buffer);
        dataView[0] = 126; // 16进制  7E
        dataView[1] = 1; //数据标识，
        var i = 1
        //console.log(device_sn)
        var j = 1;
        for (i = 1; i <= 6; i++) {    //设备编号
            //console.log(device_sn.substr((i - 1) * 2, 2))
            dataView[1 + i] = parseInt(device_sn.substr((i - 1) * 2, 2), 16)
            //console.log(device_sn.substr((i-1)*2, 2))
            j++
        }
        dataView[8] = 0;
        dataView[9] = 0; //扩展区，默认00
        dataView[10] = 0; //扩展区，默认00
        dataView[11] = 0; //扩展区，默认00
        dataView[12] = 160; // 命令A0
        dataView[13] = goodway; //出货操作 ，第一套餐
        dataView[14] = led; //led是否亮
        dataView[15] = led_time ? led_time : 15; //led亮灯时间，默认15s

        dataView[16] = 0; //保留 0
        dataView[17] = 0; //保留 0
        var check = 0
        for (let byte of dataView) {
            check += byte
        }
        //console.log(check)
        check = check - 126
        //console.log(check)
        dataView[18] = check //把和直接赋值
        dataView[19] = 126 // 16进制  7E
        return buffer
    },
    //取16位 订单号
    getOrdersn: function (minNum, maxNum) {
        var today = new Date();
        var day = today.getDate(); //获取当前日(1-31)
        var month = today.getMonth() + 1; //显示月份比实际月份小1,所以要加1
        var year = today.getYear();  //获取完整的年份(4位,1970-????)  getFullYear()
        var years = today.getFullYear();
        years = years < 99 ? "20" + years : years;
        month = month < 10 ? "0" + month : month;  //数字<10，实际显示为，如5，要改成05
        day = day < 10 ? "0" + day : day;
        var hh = today.getHours();
        hh = hh < 10 ? "0" + hh : hh;
        var ii = today.getMinutes();
        ii = ii < 10 ? "0" + ii : ii;
        var ss = today.getSeconds();
        ss = ss < 10 ? "0" + ss : ss;
        var dada = years.toString() + month.toString() + day.toString() + hh.toString() + ii.toString() + ss.toString();
        switch (arguments.length) {
            case 1:
                return dada + parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return dada + parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },
    SendTouch: function () {//发送二进制数据给设备开锁或者出货---新主板
        if (app.globalData.connected) {
            var order = bin.getOrdersn(10, 99)
            var hd = '1,1'
            var strarr = new Array(); //定义一数组
            strarr = hd.split(","); //字符分割
            //console.log(strarr)
            //console.log('订单号：' + order)
            var device_sn = 'fe45e2f4bff6';//mac 地址先设定死
            // var buffer = bin.touch(order, strarr[0], 1, 10, device_sn)  //dv 就是发送给蓝牙的数据-最新协议
            var buffer = bin.touchold(strarr[0], 1, 10, device_sn)  //dv 就是发送给蓝牙的数据
            //console.log(buffer)
            //console.log(app.globalData.connectedDeviceId)
            //console.log(app.globalData.services[0].uuid)
            //console.log(app.globalData.characteristics[0].uuid)
            //console.log(app.globalData.characteristics)
            uni.writeBLECharacteristicValue({
                deviceId: app.globalData.connectedDeviceId,
                serviceId: app.globalData.services[0].uuid,
                characteristicId: app.globalData.characteristics[1].uuid,
                value: buffer,
                success: function (res) {
                    console.log(res)
                    console.log('发送成功12')
                },
                fail: function (res) {
                    console.log('发送失败')
                    console.log(res)
                }
            })
        }
        else {
            uni.showModal({
                title: '提示',
                content: '蓝牙已断开',
                showCancel: false,
                success: function (res) {
                    app.globalData.searching = true
                }
            })
        }
    },
    SendMachine: function () {//发送二进制数据给设备开锁或者出货
        if (app.globalData.connected) {
            var order = bin.getOrdersn(10, 99)
            var hd = app.globalData.inputText
            var strarr = new Array(); //定义一数组
            strarr = hd.split(","); //字符分割
            //console.log(strarr)
            var buffer = bin.active(order, '0x65', strarr[0], strarr[1])  //dv 就是发送给蓝牙的数据
            //console.log(buffer)
            //console.log('tahtlll')
            //console.log(app.globalData)
            uni.writeBLECharacteristicValue({
                deviceId: app.globalData.connectedDeviceId,
                serviceId: app.globalData.services[0].uuid,
                characteristicId: app.globalData.characteristics[0].uuid,
                value: buffer,
                success: function (res) {
                    console.log(res)
                    console.log('发送成功12')
                }
            })
        }
        else {
            uni.showModal({
                title: '提示',
                content: '蓝牙已断开',
                showCancel: false,
                success: function (res) {

                }
            })
        }
    },
    Search: function () {//搜索附件的蓝牙设备
        if (!app.globalData.searching) { // 未搜索蓝牙
            uni.closeBluetoothAdapter({     // 关闭微信其他的蓝牙连接
                success: function (res) {
                    console.log("closeBluetoothAdapter().success:" + res);
                },
                fail: function (res) {
                    console.log("closeBluetoothAdapter().fail:" + res);
                },
                complete: function (res) {
                    console.log("closeBluetoothAdapter().complete:" + res);
                    uni.openBluetoothAdapter({ // 初始化蓝牙模块
                        success: function (res) {
                            //console.log(res)
                            uni.getBluetoothAdapterState({
                                success: function (res) {
                                    //console.log(res)
                                }
                            })
                            uni.startBluetoothDevicesDiscovery({
                                //services: ['FEE7'],
                                //allowDuplicatesKey: false,
                                success: function (res) {
                                    console.log('开始获取列表')
                                    //console.log(res)
                                    console.log('binary showLoading 225 : ');
                                    uni.showLoading({ title: '搜索蓝牙设备中...', })
                                    app.globalData.searching = true;
                                }
                            })
                        },
                        fail: function (res) {
                            uni.showModal({
                                title: '提示',
                                content: '请检查手机蓝牙是否打开',
                                showCancel: false,
                                success: function (res) {

                                }
                            })
                        }
                    })
                }
            })
        } else {
            uni.stopBluetoothDevicesDiscovery({
                success: function (res) {
                    uni.showModal({
                        title: '提示',
                        content: '未搜索到设备，请重新扫码进入',
                        showCancel: false,
                        success: function (res) {
                            //console.log(res)
                            console.log('停止蓝牙搜索');
                        }
                    });
                }
            })
        }
    },
    Zdconnect: function (s) {//连接蓝牙
        var bin = this
        console.log('binary hideLoading 262 : ');
        uni.hideLoading();
        console.log('binary showLoading 263 : ');
        uni.showLoading({
            title: '连接蓝牙设备中...',
        })
        //console.log('ssssssss' + s.deviceId)
        //console.log(app.globalData.connected)
        if (!app.globalData.connected) {
            uni.createBLEConnection({
                deviceId: s.deviceId,
                success: function (res) {
                    uni.stopBluetoothDevicesDiscovery({//停止蓝牙搜索
                        success: function (res) {
                            app.globalData.searching = true;
                        }
                    })
                    bin.Bleinit();
                },
                fail: function (res) {
                    //console.log(res)
                    console.log('binary hideLoading 283 : ');
                    uni.hideLoading()
                    console.log('binary showLoading 286 : ');
                    uni.showModal({
                        title: '提示',
                        content: '连接失败',
                        showCancel: false
                    })
                }
            })
        }

    },
    Bleinit: function () {//获取蓝牙设备特征值
        var bin = this;
        uni.getBLEDeviceServices({
            deviceId: app.globalData.connectedDeviceId,
            success: function (res) {
                app.globalData.services = res.services
                uni.getBLEDeviceCharacteristics({
                    deviceId: app.globalData.connectedDeviceId,
                    serviceId: res.services[0].uuid,
                    success: function (res) {
                        app.globalData.characteristics = res.characteristics
                        uni.notifyBLECharacteristicValueChange({
                            state: true,
                            deviceId: app.globalData.connectedDeviceId,
                            serviceId: app.globalData.services[0].uuid,
                            characteristicId: app.globalData.characteristics[0].uuid,
                            success: function (res) {
                                app.globalData.connected = true
                                //亮灯
                                bin.lightOn();
                                console.log('binary hideLoading 316 : ');
                                uni.hideLoading()
                                console.log('binary showToast 318 : ');
                                uni.showToast({
                                    title: '设备连接成功',
                                    icon: 'success',
                                    duration: 1000
                                })
                                console.log(res)
                                console.log('启用notify成功')
                            }
                        })
                    }
                })
            }
        })
    },
    newBleres: function (recval) {
        //let recval = bin.ab2hex(res.value)
        console.log('蓝牙主板通知：' + recval)
        var newArray = recval.map(item => {
            return parseInt(item, 16);
        });
        var check = 0;
        for (let i = 1; i <= 18; i++) {
            check += newArray[i]
        }
        var buffer = new ArrayBuffer(2)
        var dataView = new Uint8Array(buffer)
        dataView[0] = check;
        if (newArray[0] == 126) {
            var lres = {}
            //代表蓝牙新主板-接收成功
            //获取设备sn
            //var recvalarr = new Array(); //定义一数组
            //recvalarr = recval.split(","); //字符分割
            var str = '';
            for (var i = 2; i < 8; i++) {
                str = str + recval[i]
            }
            lres.device_sn = str
            //console.log(newArray)
            //电量
            var electric = newArray[8];
            //console.log(electric)
            lres.electric = electric
            //
            var out = newArray[11];
            var led = newArray[12];
            if (out == 0) {
                lres.out = 1
            }
            if (out == 1) {
                lres.out = 0
            }
            lres.led = led

            //订单
            var order_sn = [];
            for (var j = 13; j < 17; j++) {
                if (newArray[j] < 10) {
                    order_sn.push('0' + newArray[j])
                } else {
                    order_sn.push(newArray[j])
                }
            }
            var ostr = order_sn.join('');
            lres.order_sn = ostr
            console.log(lres)
            return lres;
        }
        return false;
    },
    Bleres: function (recval) {
        //广州新蓝牙主板协议处理
        var redata = {}
        if (recval[0] == '7e' && recval[19] == '7e') {
            redata.electric = parseInt(recval[8], 16)  //电量
            if (recval[10] == 'b0') {
                if (recval[11] == '01') {
                    redata.out = 0 //出货异常
                }
                if (recval[11] == '00') {
                    redata.out = 1 //出货正常
                }
                if (recval[12] == '01') {
                    redata.led = 1 //亮灯正常
                } else {
                    redata.led = 0 //
                }
            }
        }
        //下沙蓝牙主板处理
        if (recval[0] == '43' && recval[2] == '01') {
            if (recval[5] == '88' && recval[6] == '03') {//出货反馈
                if (recval[7] == '00') {
                    redata.errCode = 0
                    redata.msg = '出货成功'
                } else {
                    switch (recval[7]) {
                        case '01':
                            redata.errCode = 1
                            redata.msg = '操作失败-出货失败'
                            break;
                        case '02':
                            redata.errCode = 1
                            redata.msg = '校验码错误'
                            break;
                        case '03':
                            redata.errCode = 1
                            redata.msg = '数据范围错误'
                            break;
                        case '04':
                            redata.errCode = 1
                            redata.msg = '命令不支持'
                            break;
                        default:
                            redata.errCode = 1
                            redata.msg = '未知错误类型'
                    }
                }
            }
            if (recval[5] == '82') {
                if (recval[8] == '09') {
                    //套餐异常
                }
                if (recval[8] == '11') {
                    //未出货
                }
            }
        }
        return redata
    },
    closeConnect() {// 断开设备连接
        var bin = this
        if (app.globalData.connectedDeviceId) {
            uni.closeBLEConnection({
                deviceId: app.globalData.connectedDeviceId,
                success: function (res) {
                    app.globalData.services = {}
                    app.globalData.characteristics = {}
                    app.globalData.connected = false
                    bin.closeBluetoothAdapter()
                    console.log('蓝牙断开链接成功')
                },
                fail(res) {
                }
            })
        } else {
            bin.closeBluetoothAdapter()
        }
    },
    closeBluetoothAdapter() {// 关闭蓝牙模块
        uni.closeBluetoothAdapter({
            success: function (res) {
                console.log('蓝牙模块关闭成功')
            },
            fail: function (err) {
            }
        })
    },
    lightOn: function () {//亮灯
        var bin = this;
        var device = app.globalData.device_sn;
        var deviceId = device.slice(4);//发送给蓝牙的从第5位开始取
        if (device.substr(0, 3) == "6688") {
            var buffer = this.Touchold(0, 1, 15, deviceId)
        } else if (device.substr(0, 4) == "9988") {
            var order_sn = this.getOrdersn(18, 100);
            console.log(order_sn)
            order_sn = order_sn.substring(order_sn.length - 8);
            //console.log(order_sn)
            var buffer = this.Touch(order_sn, 0, 1, 15, deviceId)
        }
        //console.log(buffer)
        uni.writeBLECharacteristicValue({
            deviceId: app.globalData.connectedDeviceId,
            serviceId: app.globalData.services[0].uuid,
            characteristicId: app.globalData.characteristics[1].uuid,
            value: buffer,
            success: function (res) {
                console.log('亮灯命令发送成功')
            },
            fail: function (res) {
                console.log('亮灯命令发送失败')
            }
        })
    },
}
var fn = new Fn();
module.exports = fn
